import re, urllib, urllib2, cookielib, lxml.html
import config, handler

class PortalHandler(handler.GenericHandler):
    service_name = 'Portal'    
    
    def getNewEntries(self):
        """
        1. Login CAS Server
            1.1 GET to retrieve JSESSIONID and hidden ticket input parameter
            1.2 POST to login
            1.3 GET with portal query param to retrieve ticket for portal
        2. Portal Server
            2.1 GET Pruefungen to retrieve link to Notenspiegel
            2.2 GET notenspiegel tab
        """
        
        content = ''
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        
        # GET CAS
        resp_cas1 = opener.open('https://cas.uni-mannheim.de/cas/login')
        # find hidden ticket parameter
        tree_cas1 = lxml.html.fromstring(resp_cas1.read())
        input_lt = lxml.html.tostring(tree_cas1.cssselect('input#lt')[0])
        ltVal = re.search('(?<=value=")[a-zA-Z0-9-]*(?=")', input_lt).group(0)
        # POST CAS
        params = {
            'username' : config.PORTAL['username'], 
            'password' : config.PORTAL['password'], 
            'submit' : 'Login',
            '_eventId' : 'submit',
            'execution' : 'e1s1',
            'lt' : ltVal
        }
        login_data = urllib.urlencode(params) 
        resp_cas2 = opener.open('https://cas.uni-mannheim.de/cas/login', login_data)
        resp_cas3 = opener.open('https://cas.uni-mannheim.de/cas/login?service=https%3A%2F%2Fportal.uni-mannheim.de/qisserver/rds%3Fstate%3Duser%26type%3D1')
        
        # GET Pruefungen
        resp_pruef = opener.open('https://portal.uni-mannheim.de/qisserver/rds?state=user&type=8&topitem=pruefungen&breadCrumbSource=portal')
        # find link to notenspiegel  
        html_pruef = resp_pruef.read().decode('utf8')
        tree_pruef = lxml.html.fromstring(html_pruef)
        anchors = lxml.html.tostring(tree_pruef.cssselect('a.auflistung2')[2])
        link_notsp = re.search('(?<=href=").*?(?=")', anchors).group(0).replace('&amp;','&')

        # GET Notenspiegel
        resp_notsp = opener.open(link_notsp)
        html_notsp = resp_notsp.read().decode('utf8')
        tree_notsp = lxml.html.fromstring(html_notsp)
        tr_notsp = tree_notsp.cssselect('table')[7]
        
        content += '%d' % len(tr_notsp)
        #content += lxml.html.tostring(table_notsp)
        #tables = tree_notsp.cssselect('table')
        for tr in tr_notsp:
            content += lxml.html.tostring(tr)
        
        return [lxml.html.tostring(entry) for entry in tr_notsp]

